package com.qqt.csr.route.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;
import com.qqt.csr.common.enums.YesOrNotEnum;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.FieldType;

import java.io.Serial;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 客服路由分发规则
 */
@Getter
@Setter
@Accessors(chain = true)
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "csr_route_distribution_rules")
public class RouteDistributionRule implements Serializable {
    @Serial
    private static final long serialVersionUID = -4614124200425624360L;
    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 租户id
     */
    @TableField(value = "tenant_id")
    private String tenantId;

    /**
     * 业务选择错误达到上限次数后操作：0 退出排队；1 随机在配置的业务中分配
     */
    @TableField(value = "biz_select_error_action")
    private Integer bizSelectErrorAction;

    /**
     * 业务选择错误次数
     */
    @TableField(value = "biz_select_error_count")
    private Integer bizSelectErrorCount;

    /**
     * 业务选择错误达到上限次数后退出排序的提示
     */
    @TableField(value = "biz_select_error_quit_tip")
    private String bizSelectErrorQuitTip;

    /**
     * 业务选择错误提示话术
     */
    @TableField(value = "biz_select_error_tip")
    private String bizSelectErrorTip;

    /**
     * 服务时间id
     */
    @TableField(value = "biz_time_id")
    private Integer bizTimeId;

    /**
     * 创建时间
     */
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    @Field(targetType = FieldType.STRING)
    private Date createTime;

    /**
     * 创建人id
     */
    @TableField(value = "creator_id")
    @Field(targetType = FieldType.STRING)
    private Long creatorId;

    /**
     * 是否移除：0 否；1 是
     */
    @TableField(value = "delete_flag")
    @TableLogic(value = "0", delval = "1")
    private Integer deleteFlag;

    /**
     * 是否启用：0 否；1 是
     */
    @TableField(value = "enable_flag")
    private Integer enableFlag;

    /**
     * 策略名称
     */
    @TableField(value = "`name`")
    private String name;

    /**
     * 排队时间上限，单位秒
     */
    @TableField(value = "queue_time_limit")
    private Integer queueTimeLimit;

    /**
     * 排队超时时间，单位秒
     */
    @TableField(value = "queue_timeout")
    private Integer queueTimeout;

    /**
     * 超时策略溢出其他组后的技能组配置
     */
    @TableField(value = "queue_timeout_cfg")
    private String queueTimeoutCfg;

    /**
     * 超时策略：0 溢出其他组；1 退出路由
     */
    @TableField(value = "queue_timeout_type")
    private Integer queueTimeoutType;

    /**
     * 访客排队话术
     */
    @TableField(value = "queue_tip")
    private String queueTip;

    /**
     * 客排队话术播报间隔，单位秒
     */
    @TableField(value = "queue_tip_interval")
    private Integer queueTipInterval;

    /**
     * 排队时间上限触发退出排队话术
     */
    @TableField(value = "quit_queue_time_limit_tip")
    private String quitQueueTimeLimitTip;

    /**
     * 退出排队触发词，多个触发词用，隔开
     */
    @TableField(value = "quit_queue_word")
    private String quitQueueWord;

    /**
     * 触发词触发退出排队话术
     */
    @TableField(value = "quit_queue_word_tip")
    private String quitQueueWordTip;

    /**
     * 非服务时间拦截话术
     */
    @TableField(value = "rest_time_in_tip")
    private String restTimeInTip;

    /**
     * 更新时间
     */
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    @Field(targetType = FieldType.STRING)
    private Date updateTime;

    /**
     * 服务时间内进线话术
     */
    @TableField(value = "work_time_in_tip")
    private String workTimeInTip;

    /**
     * 路由业务规则
     */
    @TableField(exist = false)
    private List<RouteBizRule> routeBizRuleList;

    /**
     * 获取多业务规则提示语
     *
     * @return
     */
    @JsonIgnore
    public String getMultiBizRuleTip() {
        StringBuilder stringBuilder = new StringBuilder();
        if (CollectionUtils.isNotEmpty(routeBizRuleList)) {
            List<RouteBizRule> copyList = Lists.newArrayList(routeBizRuleList);
            copyList.sort(Comparator.comparing(RouteBizRule::getId));
            for (int i = 0; i < copyList.size(); i++) {
                stringBuilder.append(i + 1).append(StringPool.DOT).append(copyList.get(i).getName()).append("<br>");
            }
        }
        return "请选择您要咨询的业务<br>" + stringBuilder;
    }

    /**
     * 选择业务规则
     *
     * @return
     */
    @JsonIgnore
    public RouteBizRule chooseBizRule(String selectName) {
        if (CollectionUtils.isEmpty(routeBizRuleList)) {
            return null;
        }

        List<RouteBizRule> copyList = Lists.newArrayList(routeBizRuleList);
        copyList.sort(Comparator.comparing(RouteBizRule::getId));
        for (int i = 0; i < copyList.size(); i++) {
            RouteBizRule bizRule = copyList.get(i);
            String index = String.valueOf( i + 1);
            if(selectName.equals(index)){
                return bizRule;
            }else if (selectName.equals(index + StringPool.DOT)) {
                return bizRule;
            } else if (selectName.equals(bizRule.getName())) {
                return bizRule;
            } else if (selectName.equals(index + bizRule.getName())) {
                return bizRule;
            }else if (selectName.equals(index + StringPool.DOT + bizRule.getName())) {
                return bizRule;
            }
        }
        return null;
    }

    /**
     * 是否退出排队词
     * @param word
     * @return
     */
    @JsonIgnore
    public boolean isQuitQueue(String word){
        if(StringUtils.isBlank(this.quitQueueWord)){
            return false;
        }
        String[] split = StringUtils.split(this.quitQueueWord, StringPool.COMMA);
        for (String s : split) {
            if(s.equalsIgnoreCase(word)){
                return true;
            }
        }
        return false;
    }

    /**
     * 构建排队提示语
     * @param num
     * @return
     */
    @JsonIgnore
    public String buildQueueTip(Integer num){
        String tip = StringUtils.replaceChars(this.queueTip, "{{num}}", num.toString());
        tip = StringUtils.replaceChars(tip, "{{exit}}", this.quitQueueWord);
        return tip;
    }

    /**
     * 是否启用路由
     * @return
     */
    @JsonIgnore
    public boolean isEnable(){
        if(this.enableFlag == null){
            return false;
        }
        return this.enableFlag.equals(YesOrNotEnum.YES.getValue());
    }

}